<template>
  <div class="component-upload-image">
    <el-upload multiple :action="uploadImgUrl" ref="uploadRef" list-type="picture-card" :limit="props.limit"
      :on-error="handleUploadError" :on-exceed="handleExceed" name="file" :on-remove="handleRemove" :data="props.extend"
      :drag="props.dragFlag" :before-upload="handleBeforeUpload" :show-file-list="showFlag" :headers="headers"
      :file-list="fileList" :on-preview="handlePictureCardPreview" :class="{ hide: fileList.length >= props.limit }"
      :on-change="dealImgChange" :disabled="props.isdisabled" :auto-upload="props.dragFlag ? true : false"
      :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload" v-if="props.dragFlag">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text" v-if="props.dragFlag">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <el-icon class="avatar-uploader-icon" v-if="!props.dragFlag">
        <!-- <plus /> -->
        <img src="@/assets/images/manage/TIANJIA.png" />

      </el-icon>
      <p v-if="!props.dragFlag">上传图片</p>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="props.fileSize">
        大小不超过 <b style="color: #f56c6c">{{ props.fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
  </div>
</template>

<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { getToken } from "@/utils/auth";
import { delOss } from "@/api/system/oss";

const props = defineProps({
  modelValue: [String, Object, Array],
  // 显示文件
  showFlag: {
    type: Boolean,
    default: true
  },
  // 是否拖拽
  dragFlag: {
    type: Boolean,
    default: false
  },
  // 附加的请求参数
  extend: {
    type: Object,
    default: {}
  },
  // 图片数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['jpg', 'jpeg', 'png'],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  //是否禁用
  isdisabled: {
    type: Boolean,
    default: true
  }
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload"); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken(), 'tenant-host-name': window.location.hostname });
const fileList = ref([]);
const showBtnDealImg = ref(true)
const noneBtnImg = ref(false)
const imgUrl = ref('')//上传图片后地址合集
const failure = ref(false)
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
watch(() => props.modelValue, val => {
  // console.log('props.modelValue', props.modelValue)
  if (val) {
    let list;
    if (list == Array.isArray(val)) {
      fileList.value = list.map(item => {
        // 此处name使用ossId 防止删除出现重名
        item = { name: item.ossId, url: item.url, ossId: item.ossId };
        return item;
      });

    } else {
      fileList.value = props.modelValue.split(",").map((item, i) => {
        item = { name: 'pic' + getRandomString(4), url: props.modelValue, ossId: 'ossId' + getRandomString(2) };
        console.log('fileList.value======', item)
        return item;
      })

    }

  } else {
    fileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });

/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
function getRandomString(len) {
  let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
    min = 0,
    max = _charStr.length - 1,
    _str = '';                    //定义随机字符串 变量
  //判断是否指定长度，否则默认长度为15
  len = len || 15;
  //循环生成字符串
  for (var i = 0, index; i < len; i++) {
    index = (function (randomIndexFunc, i) {
      return randomIndexFunc(min, max, i, randomIndexFunc);
    })(function (min, max, i, _self) {
      let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
        numStart = _charStr.length - 10;
      if (i == 0 && indexTemp >= numStart) {
        indexTemp = _self(min, max, i, _self);
      }
      return indexTemp;
    }, i);
    _str += _charStr[index];
  }
  return _str;
}

// 删除图片
function handleRemove(file, files) {
  // console.log('删除图片', file, 'files==', files)
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1) {
    let ossId = fileList.value[findex].ossId;
    delOss(ossId);
    emit("update:modelValue", fileList.value);

  }
  proxy.$emit('RemoveSuccess', files)
}

function dealImgChange(file, fileList) {
  console.log(file)
  // console.log('上传的', file)
  let type = file.raw.type
  const isType =
    type === "image/png" ||
    type === "image/jpg" ||
    type === "image/jpeg";
  let imgSize = Number(file.raw.size / 1024 / 1024) > props.fileSize;
//   if (!isType && props.fileSize == 5) {
//     proxy.$modal.msgError("图片相册只能为 jpg、png、jpeg格式!!");
//     // proxy.$emit('disable', failure.value)
//     return false;
//   }
//   else if (props.fileSize == 50 && isType) {
//     proxy.$modal.msgError("视频相册只能为mp4格式");    
//     return false;
//   }


}
// 上传成功回调
/*
 *@description:
  imgLength: 用来判断上传位置,当上传到最后一张时再抛出回调
  因为按照目前写法每次上传成功都会产生一次handleUploadSuccess,
  所以只在最后一次抛出父组件需要的回调
  resList: 抛出的返回值
  fileList: 当前组件绑定的文件数组
 *@date: 2022-07-12 14:51:08
*/
const imgLength = ref(0)
const resList = ref([])
function handleUploadSuccess(res) {
  if (res.code == 200) {
    resList.value.push(res.data)
    imgLength.value += 1
    if (imgLength.value < fileList.value.length) {
      return
    } else {
      proxy.$emit('UploadSuccess', resList.value)
      proxy.$modal.closeLoading();
      resList.value = []
      imgLength.value = 0
    }
  } else {
    proxy.$modal.msgError(res.msg);
    proxy.$modal.closeLoading();
  }
}

// 上传前loading加载
function handleBeforeUpload(file) {
  console.log('file.type', file.type)
  let isImg = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isImg = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  } else {
    isImg = file.type.indexOf("image") > -1;
  }
  if (!isImg) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }

  }
  proxy.$modal.loading("正在上传，请稍候...");
  number.value++;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(res) {
  proxy.$modal.msgError("上传失败");
  proxy.$modal.closeLoading();
  failure.value = true;
  proxy.$emit('disable', failure.value)
}
//
function submitUpload() {
  console.log(fileList.value)
  // 当表单没有图片的情况
  if (fileList.value && fileList.value.length == 0) {
    proxy.$emit('unFile')
  } else if (fileList.value[0] && fileList.value[0].status == 'success') {
    // 编辑表单时,不变动已有图片的情况
    proxy.$emit('unFile', fileList.value)
  } else {
    proxy.$refs['uploadRef'].submit();
  }
}
// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}
defineExpose({
  submitUpload
});
</script>
<style lang="scss" >
.hide .el-upload--picture-card {
  display: none;
}

.el-upload.el-upload--picture-card {
  flex-wrap: wrap;
  align-items: normal;

  i.el-icon.avatar-uploader-icon {
    margin-top: 26%;
  }

  p {
    display: block;
    width: 100%;
    text-align: center;
    margin: 0;
    padding: 0;
    height: max-content;
  }
}

.el-upload-list--picture-card .el-upload-list__item-actions {
  span {
    .el-icon {
      color: #fff !important;
    }
  }
}
</style>
